#! /bin/sh

# Source debconf library.
. /usr/share/debconf/confmodule
db_version 2.0

grepconf () {
	w=" 	" # space tab
	sq=/etc/squid/squid.conf
	# sed is cool.
	res=`sed -ne '
		s/^'$1'['"$w"']\+\([^'"$w"']\+\).*$/\1/p;
		t end;
		d;
		:end q' < $sq`
	[ -n "$res" ] || res=$2
	echo "$res"
}

grepconf2 () {
	w=" 	" # space tab
	sq=/etc/squid/squid.conf
	# sed is cool.
	res=`sed -ne '
		s/^'$1'['"$w"']\+[^'"$w"']\+['"$w"']\+\([^'"$w"']\+\).*$/\1/p;
		t end;
		d;
		:end q' < $sq`
	[ -n "$res" ] || res=$2
	echo "$res"
}

#
#	We moved from /etc/cron.d/squid to /etc/logrotate.d/squid
#
conf_fix_logrotate () {
	c=/etc/cron.daily/squid
	if [ -f $c ]
	then
		##db_text high squid/logrotate || true
		##db_go
		cp -a $c $c.disabled
		( head -1 $c
		  echo "#"
		  echo "# DISABLED - lusca now uses /etc/logrotate.d/squid"
		  echo "#            please remove this file."
		  echo "#"
		) > $c.disabled
		tail +2 $c >> $c.disabled
		rm -f $c
	fi
}


#
#
#
conf_fix_http_port () {
	w=" 	" # space tab
	if ! grep -q "^http_port[$w]*" /etc/squid/squid.conf
	then
		if grep -q "^# http_port[$w]*" /etc/squid/squid.conf
		then
      		sed -e 's/^# http_port\(.*\)$/http_port\1/' \
      			< /etc/squid/squid.conf > /etc/squid/squid.conf.TMP && \
      		mv /etc/squid/squid.conf.TMP /etc/squid/squid.conf
		else
			echo >> /etc/squid/squid.conf
			echo "http_port 3128" >> /etc/squid/squid.conf 
		fi
	fi
}


case "$1" in
	configure)
		if [ -e /etc/squid/conffile-moved ] ; then
			rm /etc/squid/conffile-moved
		fi

		if [ ! -f /etc/squid/squid.conf ]; then
			cp /usr/share/doc/squid/examples/squid.conf \
				/etc/squid/squid.conf
			chmod 0600 /etc/squid/squid.conf
		fi

		conf_fix_logrotate
		conf_fix_http_port

		#
		# Chown the directories.
		#
		dir=`grepconf2 cache_dir /var/spool/squid`
        usr=`grepconf cache_effective_user proxy`
		grp=`grepconf cache_effective_group proxy`
		
	 
		#
		# Create spool dirs if they don't exist.
		#
		if [ -d "$dir" -a ! -d "$dir/00" ]
		then
			echo "Creating lusca/squid spool directory structure"
			/usr/sbin/squid -z
		fi

		#
		# Install /etc/default/lusca file if it doesn't
		# exist yet.
		#
		if [ ! -f /etc/default/lusca ]
		then
			cp /usr/share/doc/lusca/examples/default.lusca \
				/etc/default/lusca
			chmod 644 /etc/default/lusca
		fi

		#
		# If winbind is installed, add proxy user to winbindd_priv
		# group
		#
		getent group winbindd_priv >/dev/null 2>&1 &&
			adduser --quiet proxy winbindd_priv

		;;
	abort-upgrade|abort-remove|abort-deconfigure)
		;;
	*)
		#
		#	Unknown action - do nothing.
		#
		exit 0
		;;
esac

db_stop

#
#	Update links if needed and start squid.
#
update-rc.d squid defaults 30 >/dev/null

cd /

invoke-rc.d squid restart
